/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.DetermineLogin;
import com.mxg.blog.common.ResultCode;
import com.mxg.blog.entity.ArticleCategory;
import com.mxg.blog.service.ArticleCategoryService;
import com.mxg.blog.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/30 5:25
 * 添加文章分类
 */
@Controller
public class AddCategory {
    CqLogger cqLogger = CqLogger.getInstance();

    private final ArticleCategoryService articleCategoryService;
    private final UserService userService;

    public AddCategory(ArticleCategoryService articleCategoryService, UserService userService){
        this.articleCategoryService = articleCategoryService;
        this.userService = userService;
    }

    @PostMapping("api/addCategory")
    public ResponseEntity<Map<String, Object>> addCategory(@RequestBody Map<String, String> requestMap){
        Map<String, Object> resultMap = new HashMap<>();

        DetermineLogin determineLogin = DetermineLogin.getInstance(requestMap.get("userAccount"), userService);

        // 验证是否登录
        if(determineLogin.startJudge().equals(DetermineLogin.NOT_LOGIN)){
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_NOT_LOGIN);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_NOT_LOGIN);
            return ResponseEntity.ok(resultMap);
        }

        // 获取分类名
        String categoryName = requestMap.get("categoryName");

        // 验证该分类名是否存在
        ArticleCategory articleCategory = articleCategoryService.getArticleCategoryIdByName(categoryName);

        if (articleCategory == null)
        {
            articleCategoryService.addArticleCategory(categoryName);
            resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);
            resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);
        }else{
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_WRONG_EDIT_CATEGORY);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_WRONG_EDIT_CATEGORY);
        }

        return ResponseEntity.ok(resultMap);
    }
}
